<template>
    <div>
      <div class="gva-search-box">
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          
          <el-form-item label="">
            <el-input v-model="searchInfo.ID" placeholder="请输入数据ID" />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button icon="refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="gva-table-box">
        <div class="gva-btn-list">
          <el-button type="primary" icon="plus" @click="openDrawer('新增', null)">新增共享数据</el-button>
         <!--  <el-button icon="delete" :disabled="!selectedUsers.length" @click="onDelete">删除</el-button> -->
          <!-- <el-button icon="refresh" @click="onFresh">刷新</el-button>
          <ExportExcel template-id="" :limit="9999" /> -->
          <ImportExcel template-id="" @on-success="getTableData" />
        </div>
        <el-table :data="sortedData" @selection-change="handleSelectionChange" @sort-change="sortChange">
         <!--  <el-table-column type="selection" width="55" /> -->
         <el-table-column align="left" label="序号" min-width="50" v-slot="scope">
          {{ (page - 1) * pageSize + scope.$index + 1 }}
        </el-table-column>
          <el-table-column align="left" label="数据ID" min-width="150" prop="ID" sortable="custom" />
          <el-table-column align="left" label="数据来源" min-width="180" prop="Source">
            <template #default="scope">
              <span>{{scope.row.Source?'其他用户':'用户'}}</span>
            </template>
          </el-table-column>

          <el-table-column align="left" label="数据状态" min-width="150">
            <template #default="scope">
              <el-select v-model="scope.row.ShareStatus" @change="toggleStatus(scope.row)">
                <el-option label="打开" value="1"></el-option>
                <el-option label="待机" value="2"></el-option>
                <el-option label="关闭" value="0"></el-option>
              </el-select>
            </template>
        </el-table-column>
          <el-table-column align="left" label="修改时间" min-width="150" prop="UpdatedAt" sortable="custom" >
            <template #default="scope">
            {{ formatDate(scope.row.UpdatedAt) }}
          </template>
          </el-table-column>
          <el-table-column align="left" fixed="right" label="操作" width="200">
            <template #default="scope">
              <el-button icon="edit" type="primary" link @click="openDrawer('编辑', scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="gva-pagination">
          <el-pagination
              :current-page="page"
              :page-size="pageSize"
              :page-sizes="[10, 30, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
          />
        </div>
        
      </div>
  
      <!-- 新增/编辑用户抽屉 -->
      <el-drawer v-model="drawerVisible" size="60%" :before-close="closeDrawer" :show-close="false">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="text-lg">{{ drawerTitle }}</span>
            <div>
              <el-button @click="closeDrawer">取消</el-button>
              <el-button type="primary" @click="submitForm" v-show=flag>确定</el-button>
            </div>
          </div>
        </template>
  
        <el-form ref="userForm" :model="dataInfo" :rules="rules" label-width="100px">
          <el-form-item label="购买者ID" prop="buyerID">
<!--            <el-input v-model="dataInfo.buyerID" autocomplete="off"/>-->
            <el-select v-model="dataInfo.buyerID" multiple placeholder="请选择用户" style="width: 100%" @change="change">
              <el-option
                  v-for="(optionItem, optionIndex) in userData"
                  :key="optionIndex"
                  :label="optionItem.UserName"
                  :value="optionItem.ID"
              />
            </el-select>
          </el-form-item>
         <!--  <el-form-item label="销售者ID" prop="sellerID">
            <el-input v-model="dataInfo.sellerID" autocomplete="off" />
          </el-form-item> -->
          <el-form-item label="信息来源" prop="infoFrom">
            <el-input v-model="dataInfo.infoFrom" autocomplete="off" />
          </el-form-item>
          <el-form-item label="来源" prop="source">
            <el-input v-model="dataInfo.source" autocomplete="off" />
          </el-form-item>
          <el-form-item label="交易ID" prop="tradeID">
            <el-input v-model="dataInfo.tradeID" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="交易价格" prop="tradePrice">
            <el-input v-model="dataInfo.tradePrice" autocomplete="off" />
          </el-form-item>
          <el-form-item label="数据IDs" prop="dataIDs">
            <el-select v-model="dataInfo.dataIDs" multiple placeholder="请选择数据" style="width: 100%" @change="change">
              <el-option
                  v-for="(optionItem, optionIndex) in dataList"
                  :key="optionIndex"
                  :label="optionItem.DataName"
                  :value="optionItem.DataID"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="安全码" prop="securityInId">
            <el-input v-model="dataInfo.securityInId" autocomplete="off" />
          </el-form-item>
          <el-form-item label="交易时间" prop="tradeTime">
            <el-date-picker
                v-model="dataInfo.tradeTime"
                type="date"
                placeholder="请选择交易时间"
                style="width: 100%"
            />
<!--            <el-input v-model="dataInfo.tradeTime" autocomplete="off" />-->
          </el-form-item>
          <el-form-item label="数据状态" prop="ShareStatus">
            <el-input v-model="dataInfo.shareStatus" autocomplete="off"  />
          </el-form-item>
        </el-form>
      </el-drawer>
    </div>
  </template>
  <script setup>
  import { ref, reactive, computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import ExportExcel from '@/components/exportExcel/exportExcel.vue'
  import {getlistShareData, addShareData, updateShareDataStatus, GetUserList, GetDataList} from '@/api/shareManagement'

  const methodOptions = ref([
  {
    value: 'YES',
    label: '已通过',
    type: 'success'
  },
  {
    value: 'NO',
    label: '已驳回',
    type: ''
  },
  {
    value: 'APPLY',
    label: '审核中',
    type: 'warning'
  }

])
  // 原始数据
  const originalTableData = [
    
  ]
  // 原始数据
  const originalTableData1 = [

  ]
  
  // 分页相关数据
  const page = ref(1)
  const total = ref(0)
  const pageSize = ref(10)
  
  // 表格数据
  const tableData = ref([...originalTableData])
  const userData = ref([...originalTableData1])
  const dataList = ref([...originalTableData1])
  // 搜索信息
  const searchInfo = reactive({ ID: '' })
  
  // 选中的用户
  const selectedUsers = ref([])
  
  const flag=ref(false)
  // 抽屉的显示状态及标题
  const drawerVisible = ref(false)
  const drawerTitle = ref('')
  
  const detailDialog = ref(false)
// 新增的对象
  const paramT=reactive({
      buyerID :[],
      sellerID:'',
      infoFrom:'',
      tradeID:'',
      tradePrice:0,
      source:'',
      dataIDs:[],
      securityInId:'',
      tradeTime:'',
      ShareStatus:''
    })
  // 用户信息
  const dataInfo = reactive({
    ID:0,
    buyerID : [],
    sellerID : '',
    tradeID : '',
    infoFrom : '',
    tradePrice: 0,
    source : '',
    dataIDs : [],
    securityInId : '',
    tradeTime:'',
    shareStatus : 0,
    DataIDs:[''],
    DeletedAt: null,
    CreatedAt:"",
    UpdatedAt:""
  })

  const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
  }
  const change=()=> {
    this.$forceUpdate()
  }
  const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
  }

  const filteredData = computed(() => {
  const filterValue = searchInfo.ID.toLowerCase()
  return (tableData.value || []).filter(item =>
     String(item.ID).toLowerCase().includes(filterValue)
  )
})
  // 切换状态方法
const toggleStatus = async (row) => {
  try {
    if(row.ShareStatus==="1"){
      row.ShareStatus="0"
    }else{
      row.ShareStatus="1"
    }
    // 切换状态
    console.log("shareStatus:",row.ShareStatus)
    row.ShareStatus = (row.ShareStatus === "1" )? "0" : "1";
    console.log("shareStatus:",row.ShareStatus)
    const statusStr=String(row.ShareStatus)
    // 调用 updateShareData 接口更新状态
    const response = await updateShareDataStatus(row.ID, statusStr);
    getTableData()
  } catch (error) {
    console.error('请求失败', error);
    // 如果请求失败，恢复原状态
    row.ShareStatus = row.ShareStatus === 1 ? 0 : 1;
  }
};

const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

  // 表单验证规则
  const rules = ref({
    DID: [{ required: true, message: '请输入DID', trigger: 'blur' }],
    userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
    phone: [{ required: true, pattern: /^1[3456789]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }],
    bankCard: [{ required: true, message: '请输入银行卡号', trigger: 'blur' }],
    auditProgress: [{ required: true, message: '请输入审核进度', trigger: 'blur' }],
    auditStatus: [{ required: true, message: '请输入审核状态', trigger: 'blur' }]
  })
  
  // 排序信息
  const sortInfo = ref({ prop: '', order: '' })
  
  // 获取排序后的数据
  const sortedData = computed(() => {
  const data = [...filteredData.value]
  if (sortInfo.value.prop && sortInfo.value.order) {
    data.sort((a, b) => {
      let aValue = a[sortInfo.value.prop]
      let bValue = b[sortInfo.value.prop]
      if (sortInfo.value.prop === 'UpdatedAt') {
        aValue = new Date(aValue).getTime()
        bValue = new Date(bValue).getTime()
      } 
    })
  }
  console.log("源数据:",data)

  return data;
})
  
  // 搜索按钮点击事件
  const onSubmit = () => {
    const searchDID = searchInfo.ID.toLowerCase()
    tableData.value = originalTableData.value.filter(item =>
       String(item.ID).toLowerCase().includes(searchDID)
    )
    total.value = tableData.value.length
    console.log('搜索信息', searchInfo)
    // 这里可以添加请求数据的逻辑
  }
  
  const closeDetailDialog = () => {
  detailDialog.value = false
}
  // 重置按钮点击事件
  const onReset = () => {
    searchInfo.ID = ''
    tableData.value = [...originalTableData.value]
    total.value = originalTableData.value.length
    page.value = 1 // 重置分页到第1页
    console.log('重置搜索信息', searchInfo)
    // 这里可以添加请求数据的逻辑
  }
  
  // 打开抽屉
  const openDrawer = (title, row) => {
    console.log("row:",row)
    drawerTitle.value = title === '新增' ? '新增用户' : '查看详情'
    if (row) {
      dataInfo.buyerID = row.BuyerID
      dataInfo.infoFrom = row.InfoFrom
      dataInfo.tradePrice = row.TradePrice
      dataInfo.source = row.Source
      dataInfo.tradeID = row.TradeID
      dataInfo.dataIDs = row.DataIDs
      dataInfo.securityInId = row.SecurityInId
      dataInfo.tradeTime=row.TradeTime
      dataInfo.shareStatus = row.ShareStatus
    } else {
      dataInfo.buyerID = []
      dataInfo.infoFrom = ''
      dataInfo.tradePrice = 
      dataInfo.tradeID ='' 
      dataInfo.source = ''
      dataInfo.dataIDs = []
      dataInfo.securityInId = ''
      dataInfo.tradeTime=''
      dataInfo.shareStatus = ''
    }

    if(!row){
      flag.value=true
    }
    drawerVisible.value = true
    getUserData()
    getDataList()
  }
  
  // 关闭抽屉
  const closeDrawer = () => {
    drawerVisible.value = false
    flag.value=false
  }
  
  // 提交表单
  const submitForm = async () => {
    try {
    // 调用 API 添加服务
    
    /* paramT.buyerID.push(dataInfo.buyerID), */

    paramT.buyerID=dataInfo.buyerID,
    paramT.sellerID=dataInfo.sellerID,
    paramT.infoFrom=dataInfo.infoFrom,
    paramT.tradeID=dataInfo.tradeID,
    paramT.tradePrice=Number(dataInfo.tradePrice),
    paramT.source=dataInfo.source,
    paramT.dataIDs=dataInfo.dataIDs,
    paramT.securityInId=dataInfo.securityInId,
    paramT.tradeTime=dataInfo.tradeTime,
    paramT.ShareStatus=dataInfo.shareStatus,

    console.log("添加数据",paramT);
    await addShareData(paramT);

    ElMessage.success('服务新增成功');
    closeDetailDialog();
    await getTableData(); // 刷新表格数据
  } catch (error) {
    console.error('新增服务失败', error);
    ElMessage.error('新增服务失败');
  }
    closeDrawer()
  }
  
  // 删除按钮点击事件
  const onDelete = () => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      ElMessage({ type: 'success', message: '删除成功' })
      // 删除按钮逻辑
    }).catch(() => {
      console.log('取消删除')
    })
  }
  
  // 刷新按钮点击事件
  const onFresh = () => {
    ElMessageBox.confirm('确定要刷新吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      ElMessage({ type: 'success', message: '刷新成功' })
      // 刷新按钮逻辑
    }).catch(() => {
      console.log('取消刷新')
    })
  }
  
  // 选择变化处理
  const handleSelectionChange = (val) => {
    selectedUsers.value = val
    console.log('选择变化', val)
    // 选择变化逻辑
  }
  
  // 处理排序变化
  const sortChange = ({ prop, order }) => {
    sortInfo.value = { prop, order }
    console.log('排序信息', sortInfo)
  }

  const getUserData = async () => {
    try {
      const response = await GetUserList(page.value, pageSize.value);
      console.log('API response:', response.data); // 确认响应结构

      // 确保 AuditList 是数组
      if (Array.isArray(response.data.userList)) {
        userData.value = response.data.userList;
        total.value = response.data.total;
        console.log('total:', total.value);
      } else {
        console.warn('AuditList is not an array:', response.data.userList);
        userData.value = [];
        total.value = 0; // 可能需要将 total 设置为 0
        console.log('total:', total.value);
      }

      originalTableData1.value = userData.value;
      /*  total.value = response.data.TotalNum; */
      filteredData.value = [...userData.value];

      // 输出调试信息
      console.log('table:', userData.value);
      console.log('total:', total.value);
      console.log('originalTableData1:', originalTableData1.value);

    } catch (error) {
      console.error('API Error:', error);
      // ElMessage.error('获取数据失败');
    }
  };
  const getDataList = async () => {
    try {
      const response = await GetDataList(page.value, pageSize.value);
      console.log('API response:', response.data); // 确认响应结构

      // 确保 AuditList 是数组
      if (Array.isArray(response.data.list)) {
        dataList.value = response.data.list;
        total.value = response.data.total;
        console.log('total:', total.value);
      } else {
        console.warn('AuditList is not an array:', response.data.list);
        dataList.value = [];
        total.value = 0; // 可能需要将 total 设置为 0
        console.log('total:', total.value);
      }

      originalTableData1.value = dataList.value;
      /*  total.value = response.data.TotalNum; */
      filteredData.value = [...dataList.value];

      // 输出调试信息
      console.log('table:', dataList.value);
      console.log('total:', total.value);
      console.log('originalTableData1:', originalTableData1.value);

    } catch (error) {
      console.error('API Error:', error);
      // ElMessage.error('获取数据失败');
    }
  };
  // 获取表格数据
  const getTableData = async () => {
    try {
        const response = await getlistShareData(page.value, pageSize.value);
        console.log('API response:', response.data); // 确认响应结构

        // 确保 AuditList 是数组
        if (Array.isArray(response.data.list)) {
            tableData.value = response.data.list;
            total.value = response.data.total;
            console.log('total:', total.value);
        } else {
            console.warn('AuditList is not an array:', response.data.list);
            tableData.value = [];
            total.value = 0; // 可能需要将 total 设置为 0
            console.log('total:', total.value);
        }

        originalTableData.value = tableData.value;
       /*  total.value = response.data.TotalNum; */
        filteredData.value = [...tableData.value];

        // 输出调试信息
        console.log('table:', tableData.value);
        console.log('total:', total.value);
        console.log('originalTableData:', originalTableData.value);

    } catch (error) {
        console.error('API Error:', error);
        // ElMessage.error('获取数据失败');
    }
};
  

  getTableData()
  </script>
  <style scoped >
 /*  .warning {
    color: #dc143c;
  } */
  .gva-search-box {
    margin-bottom: 20px;
  }
  
  .gva-btn-list {
    margin-bottom: 20px;
  }
  
  .gva-table-box {
    margin-top: 20px;
  }
  
  .gva-pagination {
    margin-top: 20px;
  }

  .box{
    margin-left: 50px;
    margin-right: 200px;
  }

  .text-l{
    font-size: 20px;
  }
  </style>
  